package com.itboye.textileexpres.main;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.itboye.tbshopcar.listener.UIAlertView;
import com.itboye.textileexpes.beans.AppUpdateBean;
import com.itboye.textileexpes.beans.ColletionFenyeBeans;
import com.itboye.textileexpes.beans.GoodsBean;
import com.itboye.textileexpes.beans.GoodsBean.GoodsList;
import com.itboye.textileexpes.beans.GoodsTopBean;
import com.itboye.textileexpes.beans.UserBean;
import com.itboye.textileexpes.presenter.AppUpdatePresenter;
import com.itboye.textileexpes.presenter.ColloctionPresenter;
import com.itboye.textileexpes.presenter.GoodsPresenter;
import com.itboye.textileexpes.presenter.MainPresenter;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.BaseFragment;
import com.itboye.textileexpres.base.MainApplication;
import com.itboye.textileexpres.base.ResultEntity;
import com.itboye.textileexpres.base.SpPublicParams;
import com.itboye.textileexpres.top.ActivityTypeDetail;
import com.itboye.textileexpres.top.ActivityTypeTwoGoods;
import com.itboye.textileexpres.top.ActivityCarmarSearch;
import com.itboye.textileexpres.top.GoodsDetail;
import com.itboye.textileexpres.top.GoodsFragmentAdapter;
import com.itboye.textileexpres.util.IsMobileNumPhone;
import com.itboye.textileexpres.util.MyToast;
import com.itboye.textileexpres.util.SPUtils;
import com.itboye.textileexpres.util.UpdateManager;
import com.itboye.textileexpres.widget.XListView;
import com.itboye.textileexpres.widget.XListView.IXListViewListener;
import com.itboye.textileexptes.config.GlobalConfig;

public class GoodsFragment extends BaseFragment implements IXListViewListener,
		Observer {
	TextView title;
	ImageView back, img_other;
	EditText key_word;
	XListView xlist;
	GoodsFragmentAdapter adapter;
	PopupWindow popupWindow;
	View pop;
	LinearLayout no_interest;
	AppUpdatePresenter updatePresenter;
	String version;
	String update_log;
	UIAlertView dialog;
	ImageView carmar_img;
	ImageView type_img;
	GoodsPresenter goodsPresenter;
	GoodsTopBean goodsBean = new GoodsTopBean();
	int pagesize = 1;
	String pagenum = "15";
	String type = "load";
	List<GoodsTopBean.A> goodsBeanslist = new ArrayList<GoodsTopBean.A>();
	String uid, pid;
	MainPresenter mainPresenter;
	UserBean bean;
	ColloctionPresenter colloctionPresenter;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.fragment_goods;
	}

	@Override
	public void onMyActivityCreated() {
		// TODO Auto-generated method stub
		title.setText(R.string.product);
		back.setVisibility(View.GONE);
		uid = (String) SPUtils.get(getActivity(), null, SpPublicParams.UID, "");
		Log.e("hu   uid", uid);
		updatePresenter = new AppUpdatePresenter(this);
		AppUpdateBean appUpdateBean = new AppUpdateBean();
		colloctionPresenter = new ColloctionPresenter(this);
		updatePresenter.getInfo(appUpdateBean);
		goodsPresenter = new GoodsPresenter(this);
		goodsPresenter.AllQuery(uid + "", pagesize + "", pagenum);
		xlist.setPullLoadEnable(true);
		xlist.setPullRefreshEnable(true);
		xlist.setXListViewListener(this);
		pop = LayoutInflater.from(getActivity()).inflate(
				R.layout.dialog_no_interest, null);
		no_interest = (LinearLayout) pop.findViewById(R.id.no_interest);
		version = getAppVersionName(getActivity());
		OnClick();
		adapter = new GoodsFragmentAdapter(getActivity(), goodsBeanslist,
				deleteonclick, collectiononclick);
		xlist.setAdapter(adapter);
		if ("".equals(uid) || uid == "") {

		} else {
			bean = new UserBean();
			mainPresenter = new MainPresenter(this);
			bean.setUid(uid);
			bean.setAutoLoginCode((String) SPUtils.get(getActivity(), null,
					SpPublicParams.Auto_Code, ""));
			mainPresenter.Autologin(bean);
		}

	}

	private void OnClick() {
		// TODO Auto-generated method stub
		type_img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						ActivityTypeTwoGoods.class);
				startActivity(intent);
			}
		});
		key_word.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						ActivityTypeDetail.class);
				startActivity(intent);
			}
		});
		carmar_img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						ActivityCarmarSearch.class);
				intent.putExtra("from", "top");
				startActivity(intent);
			}
		});

		img_other.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

			}
		});
		xlist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if ("p".equals(goodsBeanslist.get(arg2 - 1).getType())) {
					Intent intent = new Intent(getActivity(), GoodsDetail.class);
					intent.putExtra("pid", goodsBeanslist.get(arg2 - 1)
							.getInfo().get(0).getId());
					startActivity(intent);
				}

			}
		});

	}

	OnClickListener deleteonclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			final int posion = (Integer) v.getTag();
			if (uid == "" || "".equals(uid)) {
				toast("还未登录");
				return;
			} else {

				no_interest.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v1) {
						// TODO Auto-generated method stub
						// MyToast.toast("delete");

						for (int i = 0; i < goodsBeanslist.get(posion)
								.getInfo().size(); i++) {
							colloctionPresenter.onDeleteShopcar(uid,
									goodsBeanslist.get(posion).getInfo().get(i)
											.getId());
						}

						//
						// goodsBeanslist.remove(posion);
						adapter.notifyDataSetChanged();
						popupWindow.dismiss();

					}

				});
				popupWindow = new PopupWindow(pop, LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT);
				popupWindow.setOutsideTouchable(true);
				popupWindow.setBackgroundDrawable(new BitmapDrawable());
				int[] location = new int[2];
				v.getLocationOnScreen(location);
				popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0]
						- ChangeToDP(100), location[1] - ChangeToDP(10));
			}
		}
	};
	OnClickListener collectiononclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Islogin();
			ColletionFenyeBeans model = new ColletionFenyeBeans();
			model.setUid(uid);
			model.setFType("1");
			if ("p".equals(goodsBeanslist.get((int) v.getTag()).getType())) {
				Islogin();
				for (int i = 0; i < goodsBeanslist.get((Integer) v.getTag())
						.getInfo().size(); i++) {
					model.setIds(goodsBeanslist.get((Integer) v.getTag())
							.getInfo().get(i).getId());
					System.out.println("goodsBeansID"
							+ goodsBeanslist.get((Integer) v.getTag())
									.getInfo().get(i).getId());
					colloctionPresenter.add(model);
				}

			}

		}
	};

	void Islogin() {
		if (uid == "" || "".equals(uid)) {
			toast("还未登录");
			return;

		} else {

		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = super.handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == AppUpdatePresenter.version_success) {
				AppUpdateBean appUpdateBean = (AppUpdateBean) entity.getData();
				SPUtils.put(MainApplication.getContext(), null,
						SpPublicParams.RMB_rate, appUpdateBean.getDOLLOR_RATE());// 汇率
				if (version.equals(appUpdateBean.getVersion() + "")) {

				} else {
					if ("1".equals(IsMobileNumPhone.isCheckd())
							|| "".equals(IsMobileNumPhone.isCheckd())) {
						onManager(appUpdateBean);
					}

				}
			} else if (entity.getEventType() == AppUpdatePresenter.version_fail) {
				MyToast.toast("版本解析失败");
			}
			if (entity.getEventType() == MainPresenter.AutoLoginSuccess) {
				AutoLoginSuccess(entity);
			} else if (entity.getEventType() == MainPresenter.AutoLoginFail) {
				// toast("自动登陆失败");
				MyToast.toast(entity.getData() + "");

			}
			if (entity.getEventType() == GoodsPresenter.Top_success) {

				if (type.equals("load")) {
				} else {
					goodsBeanslist.clear();
				}
				goodsBean = (GoodsTopBean) entity.getData();
				goodsBeanslist.addAll(goodsBean.getList());
				adapter.notifyDataSetChanged();
				stop();
			} else if (entity.getEventType() == GoodsPresenter.Top_fail) {
				MyToast.toast(entity.getData() + "");
				stop();

			}
			if (entity.getEventType() == ColloctionPresenter.ColloctAdd_success) {
				Intent intent = new Intent("UpDateCollection");
				getActivity().sendBroadcast(intent);
				MyToast.toast("" + entity.getData());
			} else if (entity.getEventType() == ColloctionPresenter.ColloctAdd_fail) {
				MyToast.toast("" + entity.getData());
			} else if (entity.getEventType() == ColloctionPresenter.Delete_success) {
				MyToast.toast(entity.getData() + "");
			} else if (entity.getEventType() == ColloctionPresenter.Delete_fai) {
				MyToast.toast("" + entity.getData());
			}

		}
	}

	/**
	 * 版本更新
	 */
	public void onManager(AppUpdateBean appUpdateBean) {
		UpdateManager manager = new UpdateManager(getActivity(),
				appUpdateBean.getAndroid_update_log() + "",
				appUpdateBean.getDownloadurl());
		manager.checkUpdateInfo();
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		type = "clean";
		goodsPresenter.AllQuery(uid, "" + 1, pagenum);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		type = "load";
		pagesize++;
		goodsPresenter.AllQuery(uid, "" + pagesize, pagenum);
	}

	void stop() {
		xlist.stopRefresh();
		xlist.stopLoadMore();
	}

	void AutoLoginSuccess(ResultEntity entity) {
		// LoginController.setLoginState(new LoginedState());
		Intent intent2 = new Intent("newshead");
		getActivity().sendBroadcast(intent2);
		Intent intent = new Intent("LoginSuccess");
		getActivity().sendBroadcast(intent);
		UserBean bean = (UserBean) entity.getData();
		SPUtils.put(getActivity(), null, SpPublicParams.UID, bean.getUid() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.USER_NAME,
				bean.getUsername() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.PASSWORD,
				bean.getPassword() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.NICK_NAME,
				bean.getNickname() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.PHONE_MODEL,
				bean.getMobile() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.realname,
				bean.getRealname() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.USERHEAD,
				bean.getHead());
		SPUtils.put(getActivity(), null, SpPublicParams.SEX, bean.getSex() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.AcceptAddress,
				bean.getDefaultAddress() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.Company,
				bean.getCompany() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.Job, bean.getJobTitle()
				+ "");
		SPUtils.put(getActivity(), null, SpPublicParams.AcceptAddress,
				bean.getLocArea() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.USERHEAD,
				bean.getHead() + "");
		SPUtils.put(getActivity(), null, SpPublicParams.WX, bean.getWeixin()
				+ "");
		SPUtils.put(getActivity(), null, SpPublicParams.IS_LOGINED, "1");
		SPUtils.put(getActivity(), null, SpPublicParams.Auto_Code,
				bean.getAutoLoginCode() + "");
		String time = String.valueOf((int) (Math.random() * 10));
		SPUtils.put(getActivity(), null, SpPublicParams.URL,
				GlobalConfig.IMAGE_HEAD + bean.getUid() + "&&random" + time);
	}
}
